# import jieba        #分词
from matplotlib import pyplot as plt  # 绘图，数据可视化
from wordcloud import WordCloud  # 词云
from PIL import Image  # 图片处理
import numpy as np  # 矩阵运算
import pymysql  # 数据库
import jieba.analyse


print("开始生成词云...")
# 准备词云所需的文字（词）
datalist = []
cnn = pymysql.connect(host='127.0.0.1', user='root', password='1234',
                      port=3306, database='news_with_keyword', charset='utf8')
cursor = cnn.cursor()
sql = 'select * from guanchazhe'
cursor.execute(sql)
for item in cursor.fetchall():
    datalist.append(item)
cursor.close()
cnn.close()

text = " "
# 取出数据库中的新闻内容，进行分词
for item in datalist:
    text = text + item[4]
cut = jieba.cut(text)
string = ' '.join(cut)

img = Image.open(r'.\static\assets\img\tree.jpg')  # 打开遮罩图片
img_array = np.array(img)  # 将图片转换为数组
wc = WordCloud(
    background_color='white',
    mask=img_array,
    font_path="msyh.ttc",  # 字体所在位置：C:\Windows\Fonts
    stopwords={"的", "是", "和", "在", "了", "也", "日", "月", "对", "为",
               "等", "他们", "将", "就", "我们", "年", "有", "他", "从",
               "而", "与", "年", "上", "表示", "但", "中", "说", "都", "并",
               "被", "还", "要", "到", "以", "已经", "时", "向", "后", "我",
               "已", "没有", "会", "地", "于", "指出", "这", '她', '把', '让',
               '这些', '同时', '通过', '称', '可能', '一些', '一个', '因为', '又'
               '可以', '以及', '来', '及', '就是', '不', '认为', '正在', '报道',
               '其', '又', '个', '这个'}
)
wc.generate_from_text(string)

# 绘制图片
fig = plt.figure(1)
plt.imshow(wc)
plt.axis('off')  # 是否显示坐标轴

# 输出词云图片到文件
plt.savefig(r'./static/assets/img/key_word.jpg', dpi=500)
# plt.savefig(r'key_word.jpg', dpi=500)

plt.show()  # 显示生成的词云图片

print("词云生成成功")